package com.gjt.serverSocket;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Guojt
 * @date 2024/9/11 8:09
 */
public class JHTTP {
    private static final Logger logger = Logger.getLogger(JHTTP.class.getCanonicalName());

    private static final int NUM_THREADS = 50;

    private static final String INDEX_FILE = "index.html";

    private  final File rootDirectory;

    private  final int port;

    public JHTTP(File rootDirectory, int port) throws IOException {
        if(!rootDirectory.isDirectory()){
            throw new IOException( rootDirectory + "does not exist as a directory");
        }
        this.rootDirectory = rootDirectory;
        this.port = port;
    }

    public void start() throws IOException {
        ExecutorService pool = Executors.newFixedThreadPool(NUM_THREADS);
        try (ServerSocket server = new ServerSocket(port)) {
            logger.info("Accepting connections on port" + server.getLocalPort());
            logger.info("Document Root: " + rootDirectory);

            while(true){
                Socket request = server.accept();
                Runnable r = new RequestProcessor(rootDirectory, INDEX_FILE, request);

                // 交给线程池执行任务
                pool.submit(r);
            }
        }
    }

    public static void main(String[] args) {
        // 得到文档跟
        File docroot;
        try {
            docroot = new File(args[0]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Usage: java JHTTP docroot port");
            return;
        }

        // 监听的端口
        int port;
        try {
            port = Integer.parseInt(args[1]);
            if(port < 0 || port > 65535)port = 80;
        } catch (RuntimeException e) {
            port = 80;
        }

        try{
            JHTTP webServer = new JHTTP(docroot, port);
            webServer.start();
        }catch (IOException e){
            logger.log(Level.SEVERE, "Server cloud not start", e);
        }

    }


}
